<template>
  <view class="container">
    <!-- 商品图片轮播 -->
    <swiper class="swiper" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="500">
      <swiper-item v-for="(image, index) in product.images" :key="index">
        <image :src="image" mode="aspectFill" class="swiper-image"></image>
      </swiper-item>
    </swiper>
    
    <!-- 商品基本信息 -->
    <view class="product-info">
      <view class="price-section">
        <text class="price">¥{{ product.price }}</text>
        <text class="original-price" v-if="product.originalPrice">¥{{ product.originalPrice }}</text>
      </view>
      <view class="name">{{ product.name }}</view>
      <view class="tags">
        <text class="tag" v-for="(tag, index) in product.tags" :key="index">{{ tag }}</text>
      </view>
    </view>
    
    <!-- 商品规格选择 -->
    <view class="spec-section">
      <view class="spec-item" @click="showSpecPopup">
        <text class="spec-label">规格</text>
        <text class="spec-value">{{ selectedSpec || '请选择规格' }}</text>
        <text class="arrow">></text>
      </view>
    </view>
    
    <!-- 商品详情 -->
    <view class="detail-section">
      <view class="section-title">商品详情</view>
      <view class="detail-content">
        <rich-text :nodes="product.detail"></rich-text>
      </view>
    </view>
    
    <!-- 底部操作栏 -->
    <view class="action-bar">
      <view class="action-icons">
        <view class="icon-item" @click="navigateToHome">
          <text class="icon">🏠</text>
          <text class="icon-text">首页</text>
        </view>
        <view class="icon-item" @click="toggleFavorite">
          <text class="icon">{{ isFavorite ? '❤️' : '🤍' }}</text>
          <text class="icon-text">收藏</text>
        </view>
        <view class="icon-item" @click="navigateToCart">
          <text class="icon">🛒</text>
          <text class="icon-text">购物车</text>
          <view class="cart-badge" v-if="cartCount > 0">{{ cartCount }}</view>
        </view>
      </view>
      <view class="action-buttons">
        <button class="add-cart-btn" @click="addToCart">加入购物车</button>
        <button class="buy-btn" @click="buyNow">立即购买</button>
      </view>
    </view>
    
    <!-- 规格选择弹窗 -->
    <uni-popup ref="specPopup" type="bottom">
      <view class="spec-popup">
        <view class="popup-header">
          <image :src="product.image" mode="aspectFill" class="popup-image"></image>
          <view class="popup-info">
            <view class="popup-price">¥{{ product.price }}</view>
            <view class="popup-stock">库存: {{ product.stock }}件</view>
          </view>
        </view>
        <view class="spec-list">
          <view class="spec-option" 
                v-for="(spec, index) in product.specs" 
                :key="index"
                :class="{ active: selectedSpec === spec }"
                @click="selectSpec(spec)">
            {{ spec }}
          </view>
        </view>
        <view class="quantity-control">
          <text class="quantity-label">数量</text>
          <view class="quantity-buttons">
            <text class="quantity-btn" @click="decreaseQuantity">-</text>
            <text class="quantity-value">{{ quantity }}</text>
            <text class="quantity-btn" @click="increaseQuantity">+</text>
          </view>
        </view>
        <button class="confirm-btn" @click="confirmSpec">确定</button>
      </view>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      product: {
        id: '',
        name: '',
        price: 0,
        originalPrice: 0,
        image: '',
        images: [],
        description: '',
        detail: '',
        stock: 0,
        sales: 0,
        tags: [],
        specs: []
      },
      selectedSpec: '',
      quantity: 1,
      isFavorite: false,
      cartCount: 0
    };
  },
  onLoad(options) {
    // 从路由参数中获取商品信息
    const productInfo = JSON.parse(decodeURIComponent(options.productInfo));
    this.product = {
      ...productInfo,
      images: [productInfo.image, productInfo.image, productInfo.image], // 示例图片
      originalPrice: productInfo.price * 1.2, // 示例原价
      stock: 100, // 示例库存
      tags: ['包邮', '正品保证', '七天无理由退换'],
      specs: ['标准装', '大包装', '礼盒装']
    };
    
    // 获取购物车数量
    this.updateCartCount();
  },
  methods: {
    updateCartCount() {
      const cart = uni.getStorageSync('cart') || [];
      this.cartCount = cart.reduce((total, item) => total + item.quantity, 0);
    },
    showSpecPopup() {
      this.$refs.specPopup.open();
    },
    selectSpec(spec) {
      this.selectedSpec = spec;
    },
    confirmSpec() {
      if (!this.selectedSpec) {
        uni.showToast({
          title: '请选择规格',
          icon: 'none'
        });
        return;
      }
      this.$refs.specPopup.close();
    },
    decreaseQuantity() {
      if (this.quantity > 1) {
        this.quantity--;
      }
    },
    increaseQuantity() {
      if (this.quantity < this.product.stock) {
        this.quantity++;
      } else {
        uni.showToast({
          title: '库存不足',
          icon: 'none'
        });
      }
    },
    toggleFavorite() {
      this.isFavorite = !this.isFavorite;
      uni.showToast({
        title: this.isFavorite ? '已收藏' : '已取消收藏',
        icon: 'success'
      });
    },
    navigateToHome() {
      uni.switchTab({
        url: '/pages/my/details/details'
      });
    },
    navigateToCart() {
      uni.switchTab({
        url: '/pages/cart/cart'
      });
    },
    addToCart() {
      if (!this.selectedSpec) {
        this.showSpecPopup();
        return;
      }
      
      // 构建购物车商品对象
      const cartItem = {
        id: this.product.id,
        name: this.product.name,
        price: this.product.price,
        image: this.product.image,
        spec: this.selectedSpec,
        quantity: this.quantity,
        stock: this.product.stock,
        category: this.product.category,
        selected: false // 用于购物车选择状态
      };
      
      // 获取现有购物车数据
      let cart = uni.getStorageSync('cart') || [];
      
      // 查找是否存在相同规格的商品
      const existingItemIndex = cart.findIndex(item => 
        item.id === cartItem.id && item.spec === cartItem.spec
      );
      
      if (existingItemIndex !== -1) {
        // 如果存在，增加数量
        const newQuantity = cart[existingItemIndex].quantity + cartItem.quantity;
        if (newQuantity > this.product.stock) {
          uni.showToast({
            title: '超出库存数量',
            icon: 'none'
          });
          return;
        }
        cart[existingItemIndex].quantity = newQuantity;
      } else {
        // 如果不存在，添加新商品
        cart.push(cartItem);
      }
      
      // 保存购物车数据
      uni.setStorageSync('cart', cart);
      
      // 更新购物车数量
      this.updateCartCount();
      
      // 提示成功
      uni.showToast({
        title: '已加入购物车',
        icon: 'success'
      });
      
      // 关闭规格选择弹窗
      this.$refs.specPopup.close();
    },
    buyNow() {
      if (!this.selectedSpec) {
        this.showSpecPopup();
        return;
      }
      
      const orderInfo = {
        product: this.product,
        spec: this.selectedSpec,
        quantity: this.quantity,
        totalPrice: this.product.price * this.quantity
      };
      
      uni.navigateTo({
        url: `/pages/order/confirm?orderInfo=${encodeURIComponent(JSON.stringify(orderInfo))}`
      });
    }
  }
};
</script>

<style>
.container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 120rpx;
}

.swiper {
  width: 100%;
  height: 750rpx;
}

.swiper-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.price-section {
  display: flex;
  align-items: baseline;
  margin-bottom: 20rpx;
}

.price {
  font-size: 48rpx;
  color: #4CAF50;
  font-weight: bold;
  margin-right: 20rpx;
}

.original-price {
  font-size: 28rpx;
  color: #999;
  text-decoration: line-through;
}

.name {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 20rpx;
}

.tags {
  display: flex;
  flex-wrap: wrap;
}

.tag {
  font-size: 24rpx;
  color: #4CAF50;
  background-color: #f0fff0;
  padding: 4rpx 12rpx;
  border-radius: 4rpx;
  margin-right: 10rpx;
  margin-bottom: 10rpx;
}

.spec-section {
  background-color: #fff;
  padding: 20rpx 30rpx;
  margin-bottom: 20rpx;
}

.spec-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 0;
}

.spec-label {
  font-size: 28rpx;
  color: #666;
}

.spec-value {
  font-size: 28rpx;
  color: #333;
}

.arrow {
  color: #999;
}

.detail-section {
  background-color: #fff;
  padding: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.detail-content {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
}

.action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 20rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
}

.action-icons {
  display: flex;
  margin-right: 30rpx;
}

.icon-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0 20rpx;
  position: relative;
}

.icon {
  font-size: 40rpx;
  margin-bottom: 4rpx;
}

.icon-text {
  font-size: 20rpx;
  color: #666;
}

.cart-badge {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  background-color: #4CAF50;
  color: white;
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 20rpx;
  min-width: 30rpx;
  text-align: center;
}

.action-buttons {
  flex: 1;
  display: flex;
}

.add-cart-btn, .buy-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 40rpx;
  font-size: 28rpx;
  margin: 0 10rpx;
}

.add-cart-btn {
  background-color: #f0fff0;
  color: #4CAF50;
  border: 1px solid #4CAF50;
}

.buy-btn {
  background-color: #4CAF50;
  color: #fff;
}

.spec-popup {
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  padding: 30rpx;
}

.popup-header {
  display: flex;
  margin-bottom: 30rpx;
}

.popup-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 10rpx;
  margin-right: 20rpx;
}

.popup-info {
  flex: 1;
}

.popup-price {
  font-size: 36rpx;
  color: #4CAF50;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.popup-stock {
  font-size: 24rpx;
  color: #999;
}

.spec-list {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 30rpx;
}

.spec-option {
  padding: 10rpx 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 30rpx;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
  font-size: 28rpx;
  color: #333;
}

.spec-option.active {
  border-color: #4CAF50;
  color: #4CAF50;
  background-color: #f0fff0;
}

.quantity-control {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.quantity-label {
  font-size: 28rpx;
  color: #333;
}

.quantity-buttons {
  display: flex;
  align-items: center;
}

.quantity-btn {
  width: 60rpx;
  height: 60rpx;
  background-color: #f5f5f5;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  color: #333;
}

.quantity-value {
  width: 80rpx;
  text-align: center;
  font-size: 32rpx;
  color: #333;
}

.confirm-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  background-color: #4CAF50;
  color: #fff;
  border-radius: 40rpx;
  font-size: 28rpx;
}
</style> 